package com.hzit.security.filter;

import com.alibaba.fastjson.JSON;
import com.hzit.constant.CommonConstant;
import com.hzit.security.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.hzit.constant.CommonConstant.LOGIN_KEY_PREFIX;


/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
public class HzitAuthenticationTokenFilter extends OncePerRequestFilter {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//1. 从请求头中得到token值
		String token = request.getHeader("token");
		//2. 判断是否有值
		if(!StringUtils.hasText(token)){
				filterChain.doFilter(request,response);
				return;
		}
		//3. 构造redis的key
		String key = getKey(token);
		//4. 从redis中得到值
		String s = redisTemplate.opsForValue().get(key);
		//5. 将其转换为LoginUser
		LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
		if(loginUser == null){
			throw new RuntimeException("请登录！");
		}
		//6. 构造出认证成功的对象
		UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
		//7. 将上面对象保存在SecurityContextHolder这个线程本地对象中
		SecurityContextHolder.getContext().setAuthentication(upat);
		//8. 放行过滤器
		filterChain.doFilter(request,response);
	}
	// 获取redis的key
	private String getKey(String token) {
		return LOGIN_KEY_PREFIX + token;
	}
}
